package com.cpic.blood.core.config;

import com.alibaba.fastjson.JSONObject;
import com.cpic.blood.core.common.R;
import com.cpic.blood.core.exception.CustomException;
import com.cpic.blood.core.service.impl.JwtUserDetailsService;
import com.cpic.blood.core.utils.JwtTokenUtil;
import com.cpic.blood.core.utils.RedisUtil;
import com.cpic.blood.core.vo.LoginUser;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@Component
@Slf4j
public class JwtRequestFilter extends OncePerRequestFilter {

    @Autowired
    private JwtUserDetailsService jwtUserDetailsService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Resource
    private RedisUtil redisUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {

        if(request.getRequestURI().contains("/user/login")){
            chain.doFilter(request, response);
            return;
        }

        try {
            // 进行过滤操作
            String token = jwtTokenUtil.resolveToken(request);
            if (token != null && jwtTokenUtil.validateToken(token)) {
                //从redis中获取用户信息
                String user = redisUtil.get(token);
                LoginUser loginUser = JSONObject.parseObject(user,LoginUser.class);
                if(Objects.isNull(loginUser)){
                    throw new CustomException("用户未登录");
                }
                String username = jwtTokenUtil.getUsernameFromToken(token);
                UserDetails userDetails = jwtUserDetailsService.loadUserByUsername(username);
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                        userDetails, null, userDetails.getAuthorities());
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
            chain.doFilter(request, response);
        } catch (Exception e) {
            // 发生异常时，设置错误响应
            HttpServletResponse httpResponse = (HttpServletResponse) response;
            httpResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); // 设置状态码
            httpResponse.setContentType("application/json"); // 设置响应类型为 JSON
            httpResponse.setCharacterEncoding("UTF-8");

            // 构造错误响应体
            String errorMessage = "jwt filter failed ：" + e.getMessage();
            R<Object> error = R.error(errorMessage);
            // 将错误信息写入响应体
            httpResponse.getWriter().write(JSONObject.toJSONString(error));
            httpResponse.getWriter().flush();
        }

    }
}